<?php

	/**
	 * Workspace@ Engine application comment!
	 * 
	 * LICENSE
	 * This application is licensed under New BSD license.
	 * Please read complete LICENSE.txt inside of root folder for more details.
	 * 
	 * We wish you good building :) 
	 * 
	 * @category   Application
	 * @package    Bootstrap
	 * @author     Nevio Vesic <nevio@workspaceat.com>
	 * @copyright  2008-2009 Workspace@ group in association with Design strategist
	 */
	require_once "Zend/Json.php";
	
	class Engine_Plugins_Installer extends Engine_Application_Abstract
	{
		
		const PACKAGE_INSTALL_BASEPATH  = ".install/";
		
		const INSTALLER_FILE_EXTENSION  = ".ini";
		
		const PACKAGE_BASEPATH          = "library/Packages/";
		
		const PACKAGE_DATATYPE          = ".zip";
		
		protected $db = null;
		
		function __construct()
		{
			$this->db = $this->databaseInstance();
		}
		
		public function installPlugin( Zend_Config_Ini $data )
		{
			
		}
		
		public function checkForPlugins()
		{
			if ( is_dir ( "library/Packages/" . self::PACKAGE_INSTALL_BASEPATH ) )
			{
				$dh = scandir ( "library/Packages/" . self::PACKAGE_INSTALL_BASEPATH );
				
				$installerfiles = array();
				
				foreach ( $dh as $possibleinstaller )
				{
					if ( eregi("".self::INSTALLER_FILE_EXTENSION."$", $possibleinstaller ) )
					{
						$installerfiles[] = $possibleinstaller;
					}
				}
				
				# ok now we have valid files for checking for new package
				foreach ( $installerfiles as $plugin )
				{
					
					if(! $fh = fopen( "library/Packages/" . self::PACKAGE_INSTALL_BASEPATH . $plugin, "r", true ) )
					{
						$data = array (
							"status" => "false",
							"message"  => "Plugin {$plugin} isn't readable. Please check permissions at your server"
						);
						
						echo Zend_Json::encode( $data );
						die();
					}
					
					$inih = new Zend_Config_Ini( "library/Packages/" . self::PACKAGE_INSTALL_BASEPATH . $plugin, "general" );
					
					# lets go install it if we have right permission for it.
					
					if( $inih -> installer -> status == "allowed" )
					{
						$a = split("".self::INSTALLER_FILE_EXTENSION."$", $plugin );
						
						# lets go check if current plugin got .rar archive
						if ( fopen( "library/Packages/" . self::PACKAGE_INSTALL_BASEPATH . $a[0] . self::PACKAGE_DATATYPE, "r", true ) )
						{
							# lets go copy it inside of real dir.
							# but first or what so ever lets go extract it from zip package anyway lol
							if ( is_dir( self::PACKAGE_BASEPATH . $a[0] ) )
							{
								chmod( self::PACKAGE_BASEPATH . $a[0], 0755 );
								
								$aa = opendir( self::PACKAGE_BASEPATH . $a[0] );
								
								while ( false !== ( $file = readdir( $aa ) ) ) 
								{
									if ( $file !== "." && $file !== ".." )
									unlink ( self::PACKAGE_BASEPATH . $a[0]. DIRECTORY_SEPARATOR . $file );
								}
								
								rmdir( self::PACKAGE_BASEPATH . $a[0] );
							}
							
							@$ziph = new ZipArchive();
							
							if ( @$ziph -> open( "library/Packages/" . self::PACKAGE_INSTALL_BASEPATH . $a[0] . self::PACKAGE_DATATYPE ) )
							{
								
								@$ziph ->extractTo( self::PACKAGE_BASEPATH . $a[0] );
								
								// it seems that all pass well so we will now go for more
								// lets go check if current db fields got existing one. if they do we do update on table row
								$frst1 = $this->db->fetchRow("SELECT * FROM packages WHERE unixname='{$inih->package->unixname}'");
								
								
								
								if ( $frst1 )
								{
									$query = "UPDATE packages SET
												status = 'true',
												name = '{$inih->package->name}',
												unixname = '{$inih->package->unixname}',
												description = '{$inih->package->description}',
												version = '{$inih->package->version}',
												author = '{$inih->package->author->details}',
												email = '{$inih->package->author->email}',
												type = '{$inih->package->type}',
												depends = '{$inih->package->depends->on}',
												content = '{$inih->package->pages->content}',
												ajax = '{$inih->package->pages->ajax}'
											WHERE unixname = '{$inih->package->unixname}'";
									$mess = "Updated";
								}
								elseif (! $frst1 ) 
								{
									$query = "INSERT INTO packages ( status, name, unixname, description, version, author, email, type, depends, content,
									          ajax, createdat) VALUES ( 'true', '{$inih->package->name}', '{$inih->package->unixname}', '{$inih->package->description}',
									          '{$inih->package->version}', '{$inih->package->author->details}', '{$inih->package->author->email}', '{$inih->package->type}',
									          '{$inih->package->depends->on}', '{$inih->package->pages->content}', '{$inih->package->pages->ajax}', NOW() )";
									$mess = "Installed";	
								}
								// execute query
								$result = $this->db->query($query);
								
								$query = null;
								$frst1 = null;
								
								if ( $result )
								{
									echo Zend_Json::encode(array(
										"status" => "true",
										"message" => "Package '{$inih->package->name}' has been successfully {$mess}!",
										"content" => "<ul class=\"simplelist\">
					<li class=\"firstfixlist\">{$inih->package->name}</li>
					<li class=\"ndfixlist\">{$inih->package->description}</li>
					<li class=\"rdfixlist\">{$mess}</li>
					<li class=\"thfixlist\">{$inih->package->version}</li>
				</ul>"
									));
								}
								else
								{
									echo Zend_Json::encode(array(
										"status" => "false",
										"message" => "Package '{$inih->package->name}' can't be installed. There is some error!",
										"content" => ""
									));
								}
							}
							else
							{
								
							}
							
						}
						
						$ziph->close();
					}
				}
			}
			else
			{
				$data = array (
					"status" => "false",
					"message"  => "Plugin base directory ( path ) can't be resolved atm. Please check script for errors ( debug ) or contact community!"
				);
			}
		}
	}

